<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="编码" prop="luckBoxCode">
              <el-input v-model="queryParams.luckBoxCode" placeholder="请输入编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="福盒名称" prop="luckBoxName">
              <el-input v-model="queryParams.luckBoxName" placeholder="请输入福盒名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="卡类型" prop="cardType">
              <el-select v-model="queryParams.cardType" placeholder="请选择卡类型" clearable >
                <el-option v-for="dict in card_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="系统模板" prop="isSystem">
              <el-select v-model="queryParams.isSystem" placeholder="请选择是否系统模板" clearable >
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" >新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="boxList" @selection-change="handleSelectionChange">
<!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="编码" align="center" prop="luckBoxCode" />
        <el-table-column label="福盒卡密" align="center" prop="luckBoxName" />
        <el-table-column label="卡类型" align="center" prop="cardType">
          <template #default="scope">
            <dict-tag :options="card_type" :value="scope.row.cardType"/>
          </template>
        </el-table-column>
        <el-table-column label="系统模板" align="center" prop="isSystem">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isSystem"/>
          </template>
        </el-table-column>
        <el-table-column label="盒子数量" align="center" prop="boxCount" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" ></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top" v-if="scope.row.isSystem !== '1' ">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-if="scope.row.isSystem !== '1' "></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改福盒对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1000px" append-to-body>
      <el-form ref="boxFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="福盒卡密名称" prop="luckBoxName" label-width="120px">
              <el-input v-model="form.luckBoxName" placeholder="请输入福盒卡密名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卡类型" prop="cardType">
              <el-select v-model="form.cardType" placeholder="请选择卡类型">
                <el-option
                  v-for="dict in card_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-card class="box-card" style="margin-top: 20px">
          <template #header>
            <div>
                            <span style="font-weight: bold">
                                <el-icon color="red">
                                    <CollectionTag />
                                </el-icon>
                                卡密内容</span>
            </div>
          </template>
          <div class="card-body">
            <el-form-item label="" label-width="0" >
              <el-table :data="form.luckBoxDetailsBos" border max-height="500px">
                <el-table-column label="序号" align="center" prop="sortNumber" width="100px">
                  <template #default="scope">
                    <span style="opacity: 0;">1</span>
                    {{ `${Number(scope.$index) + 1}` }}
                    <span style="opacity: 0;">{{ scope.row.sortNumber =Number(scope.$index) + 1
                      }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="卡密内容" align="center">
                  <template #default="scope">
                    <el-form-item label=""
                                  :prop="'luckBoxDetailsBos.' + scope.$index + '.luckBoxCarmi'"
                                  label-width="" :rules="rules.luckBoxCarmi">
                      <el-input v-model="scope.row.luckBoxCarmi" placeholder="请输入卡密内容" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" prop="sortNumber" width="100px">
                  <template #default="scope">
                    <el-popconfirm title="确定要删除该条数据吗？" icon-color="red"
                                   @confirm="ActivityListHandle(scope.$index, 'del')">
                      <template #reference>
                        <el-button type="danger" icon="Delete" circle></el-button>
                      </template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <div align="center">
              <el-link type="success" @click="ActivityListHandle('index', 'add')"
                       style="color: hotpink"><el-icon>
                <Plus />
              </el-icon>添加卡密</el-link>
            </div>
          </div>
        </el-card>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog :title="dialogView.title" v-model="dialogView.visible" width="1000px" append-to-body>
      <el-form ref="boxFormRef" :model="form" :rules="rules" label-width="80px" :disabled = "true">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="福盒名称" prop="luckBoxName">
              <el-input v-model="form.luckBoxName" placeholder="请输入福盒名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卡类型" prop="cardType">
              <el-select v-model="form.cardType" placeholder="请选择卡类型">
                <el-option
                  v-for="dict in card_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-card class="box-card" style="margin-top: 20px">
          <template #header>
            <div>
                            <span style="font-weight: bold">
                                <el-icon color="red">
                                    <CollectionTag />
                                </el-icon>
                                卡密内容</span>
            </div>
          </template>
          <div class="card-body">
            <el-form-item label="" label-width="0" >
              <el-table :data="form.luckBoxDetailsBos" border max-height="500px">
                <el-table-column label="序号" align="center" prop="sortNumber" width="100px">
                  <template #default="scope">
                    <span style="opacity: 0;">1</span>
                    {{ `${Number(scope.$index) + 1}` }}
                    <span style="opacity: 0;">{{ scope.row.sortNumber =Number(scope.$index) + 1
                      }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="卡密内容" align="center">
                  <template #default="scope">
                    <el-form-item label=""
                                  :prop="'luckBoxDetailsBos.' + scope.$index + '.luckBoxCarmi'"
                                  label-width="" :rules="rules.luckBoxCarmi">
                      <el-input v-model="scope.row.luckBoxCarmi" placeholder="请输入卡密内容" />
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>
        </el-card>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="Box" lang="ts">
import { listBox, getBox, delBox, addBox, updateBox, updateLuckBoxStatus } from '@/api/system/box';
import { BoxVO, BoxQuery, BoxForm } from '@/api/system/box/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_yes_no, card_type, open_or_close } = toRefs<any>(proxy?.useDict('sys_yes_no', 'card_type', 'open_or_close'));

const boxList = ref<BoxVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const boxFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogView = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BoxForm = {
  id: undefined,
  luckBoxCode: undefined,
  luckBoxName: undefined,
  cardType: undefined,
  isSystem: undefined,
  boxCount: undefined,
  shopId: undefined,
  luckBoxDetailsBos: [],
  deleteFlag: undefined
}
const data = reactive<PageData<BoxForm, BoxQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    luckBoxCode: undefined,
    luckBoxName: undefined,
    cardType: undefined,
    isSystem: undefined,
    boxCount: undefined,
    shopId: undefined,
    deleteFlag: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    luckBoxName: [
      { required: true, message: "福盒名称不能为空", trigger: "blur" }
    ],
    cardType: [
      { required: true, message: "卡类型不能为空", trigger: "change" }
    ],
    luckBoxCarmi: [
      { required: true, message: "卡密内容不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询福盒列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBox(queryParams.value);
  boxList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  boxFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: BoxVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.luckBoxDetailsBos = [];
  dialog.visible = true;
  dialog.title = "添加福盒卡密";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: BoxVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getBox(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改福盒";
}

/** 查看按钮操作 */
const handleView = async (row?: BoxVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getBox(_id);
  Object.assign(form.value, res.data);
  dialogView.visible = true;
  dialogView.title = "查看福盒";
}

/** 上下架按钮操作 */
const handleStatusChange = async (row?: BoxVO) => {
    if(row.isSystem == '1') {
      ElMessage.error('官方模板不允许修改')
      getList();
    }
    const _ids = row?.id;
    const res = await updateLuckBoxStatus(_ids, row.luckBoxState);
    proxy?.$modal.msgSuccess("操作成功");
    await getList();
}

/** 提交按钮 */
const submitForm = () => {
  boxFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateBox(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addBox(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: BoxVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除福盒编号为"' + row.luckBoxCode + '"的数据项？').finally(() => loading.value = false);
  await delBox(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/box/export', {
    ...queryParams.value
  }, `box_${new Date().getTime()}.xlsx`)
}

const ActivityListHandle = (index: any, operation: string) => {
  switch (operation) {
    case 'add':
      form.value.luckBoxDetailsBos.push({
        sortNumber: undefined,
        luckBoxCarmi: '',
      })
      break;
    case 'del':
      if (form.value.luckBoxDetailsBos.length == 1) {
        form.value.luckBoxDetailsBos = [{
          sortNumber: undefined,
          luckBoxCarmi: undefined,
        }]
        return
      }
      form.value.luckBoxDetailsBos.splice(index, 1)
      break;
    default:
      break;
  }
}

onMounted(() => {
  getList();
});
</script>
